<template>
	<view>
		
	</view>
</template>

<script>
export default {
	data() {
		return {
			phoneno: '',
			headimgurl:'',
			openid:'',
			unionid:'',
		};
	},
	onLoad() {
		var localData = uni.getStorageSync('localData');

		if (localData) {
			this.$router.push({ path: '/pages/index/index' });
		}
		
		//开启之后只能是公众号访问
		this.loginWithWx();
		
	},
	methods: {
		loginWithWx: function() {
			if (!uni.getStorageSync('openid') || uni.getStorageSync('openid') == undefined ) {
				this.getWxUserInfoCode();
			}
		},

		//微信公众号登录
		getWxUserInfoCode() {
			var code = this.getUrlParam('code'); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
			var local = encodeURIComponent('https://你的h5地址/h5/#/pages/login/login');
			let appid = 'appid';
			
			
			if (code == null || code === '') {
				window.location.href =
					'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+local+'&response_type=code&scope=snsapi_base&connect_redirect=1&state=#wechat_redirect';
			} else {
				this.getOpenId(code); //把code传给后台获取用户信息
			}
		},
		getOpenId(code) {
			var _this = this;
			_this.$sendRequest({
				url: 'wechat/get_open_id',
				data: {
					code: code
				},
				method: 'get',
				dataType: 'json', // 返回数据格式,
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				success: res => {
					// console.log(res.data);
					if (res.data.code == 1) {
						
						uni.setStorageSync('openid', res.data.data.openid);
						uni.setStorageSync('unionid', res.data.data.unionid);
						uni.setStorageSync('headimgurl', res.data.data.headimgurl);
						
						_this.openid = res.data.data.openid,
						_this.unionid = res.data.data.unionid,
						_this.headimgurl = res.data.data.headimgurl
					}
				}
			});
			
		},
		// 解析URL 参数
		getUrlParam(name) {
			let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
			let r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return unescape(r[2]);
			}
			return null;
		}
	},
};

</script>

<style>

</style>
